home *** CD-ROM | disk | FTP | other *** search
- Path: news.halcyon.com!usenet
- From: normanb@halcyon.com (Norm Bryar)
- Newsgroups: comp.lang.c++
- Subject: Re: casting virtual base classpointer to derived
- Date: Sat, 20 Jan 1996 00:55:05 GMT
- Organization: Northwest Nexus Inc.
- Message-ID: <4dpegi$6ci@news.halcyon.com>
- References: <DLE98M.nEI@novice.uwaterloo.ca>
- NNTP-Posting-Host: blv-pm10-ip8.halcyon.com
- X-Newsreader: Forte Free Agent 1.0.82
-
- mkalisia@novice.uwaterloo.ca (Maciej Kalisiak) wrote:
-
- >I ran into a "limitation" of C++ that I wasn't aware off, and I was
- >hoping someone out there can tell me how to get around this
- >limitation:
-
- >I have a base class Base. I derive a number of other classes from Base
- >using "virtual public". I have an array/list of Base*, which holds
- >pointers to a whole bunch of object of type Base, or any of the derived
- >ones. I take one of these pointers (Base*) and I know that it was
- >really pointing to a derived class. I try to cast to this derived class
- >but I can't (supposedly all compilers are supposed to issue an error in
- >such a case).
-
- >Any ideas of how to keep such a list of derived type objets using
- >Base*'s, or how to get around this ???
-
- >I am using Watcom v10.0
-
- No idea if Watcom 10.0 has run-time type information (RTTI), but the
- recent draft(s) of C++ have features for just this kind of problem:
-
- dyanmic_cast<Derived1 *>(pBase)
-
- The dynamic_cast will return NULL if the instance pointed to by pBase
- really isn't of type Derived1, otherwise you get a pointer cast
- appropriately. (Virtual inheritence complicates matters, but
- generally you can get where you want by cascading afew dynamic_cast
- operations to resovle ambiguities).
-
- This only works on references (or pointers), of course, and only works
- if the classes have vtables. Your polymorphic use of an array of
- Base* means you definitely have virtual functions and thus vtables, so
- this ought to work for you.
- --Norm
-
-